package es.abredatos.client.presenter;

import java.util.Iterator;
import java.util.List;

import com.google.code.gwt.geolocation.client.Coordinates;
import com.google.code.gwt.geolocation.client.Geolocation;
import com.google.code.gwt.geolocation.client.Position;
import com.google.code.gwt.geolocation.client.PositionCallback;
import com.google.code.gwt.geolocation.client.PositionError;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

import es.abredatos.client.BooksLocatorServiceAsync;
import es.abredatos.shared.Book;
import es.abredatos.shared.Library;

public class LibrariesPresenter implements Presenter {

	public interface Display {
		public void setCoordinates(double latitude, double longitude);
	}

	private BooksLocatorServiceAsync rpcService;
	private HandlerManager eventBus;
	private Display display;
	private Coordinates coordinates;

	public LibrariesPresenter(BooksLocatorServiceAsync rpcService, HandlerManager eventBus, Display display, String id) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;

		detectLocation();
		fetchLibraries(coordinates);
	}

	public void go(HasWidgets container) {
		container.clear();
		container.add((Widget) display);
	}

	private void detectLocation() {
		if (Geolocation.isSupported()) {
			Geolocation geo = Geolocation.getGeolocation();
			geo.getCurrentPosition(new PositionCallback() {

				public void onSuccess(Position position) {
					coordinates = position.getCoords();
				}

				public void onFailure(PositionError error) {
					Window.alert("Can't detect your location");
				}
			});
		}
	}

	private void fetchLibraries(final Coordinates coordinates) {
		rpcService.locateLibrary(new Book(), new AsyncCallback<List<Library>>() {

			public void onSuccess(List<Library> libraries) {

				display.setCoordinates(coordinates.getLatitude(), coordinates.getLongitude());

				for (Iterator<Library> iterator = libraries.iterator(); iterator.hasNext();) {
					Library library = iterator.next();

					display.setCoordinates(library.getLatitude(), library.getLongitude());
				}
			}

			public void onFailure(Throwable caught) {
				Window.alert("Communication fail");
			}

		});
	}

}
